package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

// 注册处理函数
func registerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		// 设置响应头为 JSON 格式
		w.Header().Set("Content-Type", "application/json")

		// 解析请求体中的 JSON 数据到 User 结构体
		var user User
		err := json.NewDecoder(r.Body).Decode(&user)
		if err != nil {
			log.Printf("Error decoding JSON: %v", err)
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}
		// fmt.Println(user)
		// 在这里可以进行注册逻辑的处理，将用户信息存储到数据库
		if user.UserType == "comuser" {
			_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_user (role, username, phonenumber, idnumber, email, password) VALUES ($1, $2, $3, $4, $5, $6)", user.UserType, user.Username, user.Phonenumber, user.Idnumber, user.Email, user.Password)
			if err != nil {
				fmt.Println("Error inserting user:", err)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
		} else if user.UserType == "business" {
			_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_business (role, username, phonenumber, idnumber, email, password) VALUES ($1, $2, $3, $4, $5, $6)", user.UserType, user.Username, user.Phonenumber, user.Idnumber, user.Email, user.Password)
			if err != nil {
				fmt.Println("Error inserting user:", err)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
		}

		// 返回注册成功的消息
		response := map[string]string{"message": "注册成功"}
		json.NewEncoder(w).Encode(response)
	}
}
